﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace ExcelImport.Validators
{
    public class ExcelUniqueValidator : IDataRowProcessor
    {
        public Dictionary<ImportProperty, List<string>> _checkUniqueProperties = new Dictionary<ImportProperty, List<string>>();

        public void Run(DataRow row, PipelineContext context)
        {
            foreach (var importProperty in context.ImportTable.ImportProperties.Where(p => p.Ordinal.HasValue && p.IsUnique))
            {
                string value = row[importProperty.Ordinal.Value]?.ToString();

                if (!string.IsNullOrEmpty(value))
                {
                    if (!_checkUniqueProperties.TryGetValue(importProperty, out var list))
                    {
                        list = new List<string>();
                        _checkUniqueProperties[importProperty] = list;
                    }

                    if (list.Exists(p => p == value))
                    {
                        context.AddValidationResult(new ValidationResult($"第{context.Index}行,{importProperty.HeaderName}为{value}的数据在Excel中已经存在"));
                    }
                    else
                    {
                        list.Add(value);
                    }
                }
            }
        }
    }
}
